package com.mysecurity.controller;

import com.mysecurity.pojo.SecurityUser;
import com.mysecurity.utils.JWTAuth;
import com.mysecurity.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Jane
 * @date 2024-07-01 15:33
 */
@Controller
public class LoginController {

    @Resource
    private AuthenticationManager authenticationManager;

    @RequestMapping("/dologin")
    @ResponseBody
    public Result<String> dologin(@RequestParam(name = "username") String username
            , @RequestParam(name="password")
    String password){

        System.out.println("username: "+ username);
        //        传入用户名和密码
        UsernamePasswordAuthenticationToken usernamePassword =
                new UsernamePasswordAuthenticationToken(username, password);

        //调用security的认证方法
        Authentication authenticate = authenticationManager.authenticate(usernamePassword);
        SecurityUser principal = (SecurityUser) authenticate.getPrincipal();
        String name = authenticate.getName();//用户名
        Object credentials = authenticate.getCredentials();//凭证(脱敏)

        System.out.println(username);
        System.out.println(principal);
        System.out.println(credentials);


        //生成jwt  类似之前的将用户的登录信息存入session
        //根据用id生成jwt
        String token =JWTAuth.generateJWT(principal);

        //存入redis

        System.out.println("----权限列表: "+principal.getAuthorities());

//        return  "您好,"+username;
        return Result.ok(token).message("登录成功");
    }

    @RequestMapping({"/","/mylogin"})
    public String mylogin(){
        return  "login";
    }

    // 负责登录失败后跳转到失败页面
    @RequestMapping("/toError")
    public String toError() {
        return "error";
    }


}
